package com.madev.isellcrazyitems;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.madev.isellcrazyitems.entity.Statement;
import com.madev.isellcrazyitems.handler.DatabaseHandler;
import com.madev.isellcrazyitems.handler.JSONController;
import com.madev.sales.R;

public class SyncActivity extends Activity {

	// Progress Dialog
	private ProgressDialog pDialog;

	Button btn;
	TextView records;

	JSONController JSONController = new JSONController();

	// url to create new product
	private static String url_sync = "http://unifiq.5kportal.com/iselldeb/executesync.php";

	// JSON Node names
	private static final String TAG_SUCCESS = "success";
	private static final String TAG_MESSAGE = "message";

	@Override
	public void onResume() {
		super.onResume();
		DatabaseHandler db = new DatabaseHandler(getApplicationContext());
		ArrayList<Statement> sts = db.getStatements();
		records.setText(null);
		for (int i = 0; i < sts.size(); i++) {

			records.append(sts.get(i).getStatement() + " ");
			records.append("\n\n");

		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.sync);

		btn = (Button) findViewById(R.id.btn_sync);
		records = (TextView) findViewById(R.id.recordsTv);

		DatabaseHandler db = new DatabaseHandler(getApplicationContext());
		ArrayList<Statement> sts = db.getStatements();
		records.setText(null);

		for (int i = 0; i < sts.size(); i++) {

			records.append(sts.get(i).getStatement() + " ");
			records.append("\n\n");
		}

		// button click event
		btn.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View view) {
				// background thread
				new ExecuteStatement().execute();
			}
		});
	}

	/**
	 * Background Async Task to execute statement
	 * */
	class ExecuteStatement extends AsyncTask<String, String, String> {

		DatabaseHandler db;

		/**
		 * Before starting background thread Show Progress Dialog
		 * */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(SyncActivity.this);
			pDialog.setMessage("Executing Statement..");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(true);
			pDialog.show();
		}

		/**
		 * Sync DB
		 * */
		@Override
		protected String doInBackground(String... args) {

			db = new DatabaseHandler(getApplicationContext());
			db.getWritableDatabase();
			ArrayList<Statement> statem = db.getStatements();
			if (!statem.isEmpty()) {

				for (int i = 0; i < statem.size(); i++) {
					// Building Parameters
					List<NameValuePair> params = new ArrayList<NameValuePair>();
					params.add(new BasicNameValuePair("statement", statem
							.get(i).getStatement()));

					// getting JSON Object
					// Note accepts POST method
					JSONObject json = JSONController.makeHttpRequest(url_sync,
							"POST", params);

					// check log cat from response
					Log.d("Create Response", json.toString());

					// check for success tag
					try {
						int success = json.getInt(TAG_SUCCESS);
						String err = json.getString(TAG_MESSAGE);
						if (success == 1) {
							// successfully sync
							db.removeStatement(statem.get(i).getStatement());
							Log.i("success", "sql executed");
							return null;
						} else {
							// failed to sync
							Log.e("syncerr", err);
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
			}
			return null;

		}

		/**
		 * After completing background task Dismiss the progress dialog
		 * **/
		@Override
		protected void onPostExecute(String file_url) {
			// dismiss the dialog once done
			pDialog.dismiss();

			DatabaseHandler db = new DatabaseHandler(getApplicationContext());
			ArrayList<Statement> sts = db.getStatements();
			records.setText(null);
			for (int i = 0; i < sts.size(); i++) {

				records.append(sts.get(i).getStatement() + " ");
				records.append("\n\n");

			}

		}

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.sync, menu);
		return true;
	}

}
